package mygame;

import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** Holds a single y-layer of voxels. Other classes typically don't deal with this, use VoxelGrid instead. */
public class VoxelLayer implements Savable {
    protected int layerNum;
    protected Map<Vector3i, Voxel> voxels = new HashMap<Vector3i, Voxel>();

    public VoxelLayer() {}

    public VoxelLayer(int layerNum) {
	this.layerNum = layerNum;
    }

    public int getLayerNum() {
	return layerNum;
    }

    public void setLayerNum(int layerNum) {
	this.layerNum = layerNum;
    }

    public void addVoxel(Voxel voxel) {
        voxels.put(voxel.getVoxelGridLocation(), voxel);
    }

    public void removeVoxel(Voxel voxel) {
        voxels.remove(voxel.getVoxelGridLocation());
    }

    public Voxel getVoxelAtLocation(Vector3i voxelGridLocation) {
        return voxels.get(voxelGridLocation);
    }

    public boolean isVoxelAtLocation(Vector3i voxelGridLocation) {
        return voxels.containsKey(voxelGridLocation);
    }

    public Set<Voxel> getVoxels() {
	return new HashSet<Voxel>(voxels.values());
    }

    public void write(JmeExporter ex) throws IOException {
	OutputCapsule capsule = ex.getCapsule(this);
	capsule.write(layerNum, "layerNum", 0);
	capsule.writeSavableArrayList(new ArrayList<Voxel>(voxels.values()), "voxels", new ArrayList<Voxel>());
    }

    @SuppressWarnings("unchecked")
    public void read(JmeImporter im) throws IOException {
	InputCapsule capsule = im.getCapsule(this);
	layerNum = capsule.readInt("layerNum", 0);
	ArrayList<Voxel> voxs = capsule.readSavableArrayList("voxels", new ArrayList<Voxel>());
	for(Voxel voxel : voxs) {
	    addVoxel(voxel);
	}
    }
}
